package com.winbaoxian.testng.service;

import com.winbaoxian.testng.model.entity.ApiEntity;
import com.winbaoxian.testng.model.entity.ProjectEntity;
import com.winbaoxian.testng.repository.ApiRepository;
import com.winbaoxian.testng.repository.ProjectRepository;
import com.winbaoxian.testng.utils.StringExtUtils;
import com.winbaoxian.testng.utils.UrlParserUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service
public class AnalysisService {

    @Resource
    private ApiRepository apiRepository;
    @Resource
    private ProjectRepository projectRepository;

    /**
     * 分析接口的完成状态
     *
     * @param projectId
     * @param requestUrl
     */
    @Transactional
    public void analysisApiFinishFlag(Long projectId, String requestUrl) {
        if (StringUtils.isBlank(requestUrl) || projectId == null) {
            return;
        }
        String requestPath = UrlParserUtils.INSTANCE.parseStrictRequestPath(requestUrl);
        ApiEntity entity = apiRepository.findTopByProjectIdAndApiUrlAndDeletedFalse(projectId, requestPath);
        //替换最后个数字
        if (entity == null) {
            String requestPathLikeStr = StringExtUtils.INSTANCE.replaceLast(requestPath, "/(\\d+)([/]?)", "/{%}$2");
            if (!StringUtils.equals(requestPath, requestPathLikeStr)) {
                entity = apiRepository.findTopByProjectIdAndApiUrlLikeAndDeletedFalse(projectId, requestPathLikeStr);
            }
        }
        //替换所有数字查找
        if (entity == null) {
            String requestPathLikeStr = StringUtils.replacePattern(requestPath, "/(\\d+)([/]?)", "/{%}$2");
            if (!StringUtils.equals(requestPath, requestPathLikeStr)) {
                entity = apiRepository.findTopByProjectIdAndApiUrlLikeAndDeletedFalse(projectId, requestPathLikeStr);
            }
        }
        if (entity == null || BooleanUtils.isTrue(entity.getFinishFlag())) {
            return;
        }
        entity.setFinishFlag(Boolean.TRUE);
        apiRepository.save(entity);
    }

    @Transactional
    public void statisticApiFinishData(Long projectId) {
        if (projectId == null) {
            return;
        }
        long targetCount = apiRepository.countByProjectIdAndTargetFlagTrueAndDeletedFalse(projectId);
        long finishCount = apiRepository.countByProjectIdAndTargetFlagTrueAndFinishFlagTrueAndDeletedFalse(projectId);
        ProjectEntity entity = projectRepository.getOne(projectId);
        if (entity == null) {
            return;
        }
        entity.setTargetCount(targetCount);
        entity.setFinishCount(finishCount);
        projectRepository.save(entity);
    }

}
